package com.lagou.controller;

import com.lagou.mapper.ResultMapper;
import com.lagou.pojo.Product;
import com.lagou.pojo.ProductVo;
import com.lagou.service.ProductService;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.network.Mode;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Properties;

@RestController
@RequestMapping("/product")
public class ProductController {
    public static String topic = "products";
    @Autowired
    private ProductService productService;

    @RequestMapping("/add")
    public String addProduct(@RequestBody Product product) {
        int i = productService.insert(product);
        productionMessage(product.getId());
        return "添加成功";
    }

    // 查询结果
    @RequestMapping("/search")
    public String search(@RequestBody ProductVo productVo) {
        List<Product> list = productService.search(productVo);
        System.out.println(list);
        return list.toString();
    }

    public void productionMessage(int msg) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.128:9092,192.168.200.128:9093,192.168.200.128:9094");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);


        //设置消息内容
        String id = Integer.toString(msg);
        //将消息内容封装到ProducerRecord中
        ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, id);
        kafkaProducer.send(record);
        System.out.println("消息发送成功:" + msg);
        kafkaProducer.close();
    }


}
